package com.appspot.graph_wave;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.jdo.JDOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GraphSourceServlet extends HttpServlet {
	private static final Pattern urlPattern = Pattern.compile(".*/(\\d+).gv");

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		String uri = req.getRequestURI();
		Matcher match = urlPattern.matcher(uri);
		if (match.matches()) {
			Long id = Long.parseLong(match.group(1));
			try {
				Graph g = Graph.retrieveContent(id);
				resp.getWriter().println(g.getContent());
			} catch (JDOException e) {
				resp.getWriter().println("Error: No entry for given id.");
			}
		} else {
			resp.getWriter().println("Error: Unable to parse request.");
		}
	}
}